package com.buddy.summary.code.annotation;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HandlerInterceptorAdapter SpringMVC的"拦截器"/适配器
 */
public class PlatHandlerInterceptorAdapter extends HandlerInterceptorAdapter {


    /**
     * 在业务处理器处理请求之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取Controller注解,Controller检查是否需要权限验证
            PlatePermission platePermission = handlerMethod.getMethod()
                    .getDeclaringClass().getAnnotation(PlatePermission.class);
            if (platePermission != null && !platePermission.validate()){
                return super.preHandle(request,response,handler);
            }
            //获取方法注解,检查是否需要权限验证
            platePermission = handlerMethod.getMethod().getAnnotation(PlatePermission.class);
            if (platePermission != null && !platePermission.validate()){
                return super.preHandle(request,response,handler);
            }
            //TODO 验证权限

        }

        return super.preHandle(request, response, handler);
    }

    /**
     * 在业务处理器处理请求执行完成后,生成视图前调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源包,返回处理,可以根据ex是否为null判断是否发生了异常,进行日志记录
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
